package com.flyou.ccnucenter.ui.activity.henuBeside.lostFind;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadBatchListener;
import com.codetroopers.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment;
import com.codetroopers.betterpickers.calendardatepicker.MonthAdapter;
import com.codetroopers.betterpickers.radialtimepicker.RadialTimePickerDialogFragment;
import com.e1858.myalertview.AlertView;
import com.e1858.myalertview.OnItemClickListener;
import com.flyou.ccnucenter.R;
import com.flyou.ccnucenter.adapter.LostFoundPsotPhotoAdapter;
import com.flyou.ccnucenter.domain.Lost;
import com.flyou.ccnucenter.ui.activity.BaseActivity1;
import com.flyou.ccnucenter.ui.activity.gallery.GalleryActivity;
import com.flyou.ccnucenter.utils.BitmapTool;
import com.flyou.ccnucenter.utils.BmobErrorCodeUtils;
import com.flyou.ccnucenter.utils.GalleryImageLoader;
import com.flyou.ccnucenter.utils.LoginUtils;
import com.flyou.ccnucenter.utils.MyLog;
import com.flyou.ccnucenter.utils.SDCardUtils;
import com.flyou.ccnucenter.widget.ClearEditText;
import com.flyou.photopicker.GalleryHelper;
import com.flyou.photopicker.model.PhotoInfo;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import org.joda.time.DateTime;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.SaveListener;


public class AddLostFoundActivity extends BaseActivity1 implements View.OnClickListener, OnItemClickListener, CalendarDatePickerDialogFragment.OnDateSetListener, RadialTimePickerDialogFragment.OnTimeSetListener, AdapterView.OnItemClickListener, TextWatcher {
    private static final String FRAG_TAG_DATE_PICKER = "fragment_date_picker_name";
    private static final String FRAG_TAG_TIME_PICKER = "timePickerDialogFragment";
    public static final int GALLERY = 12306;
    public static final int GALLERYBACKOK = 10010;


    private int totalNum = 35;
    private int selectionStart;
    private int selectionEnd;
    private CharSequence tempCount;

    private String feedbackTypes[] = {"书籍", "书包", "证件", "数码", "其他"};
    private String currentType = "书籍";

    private String LostFindDataTime;

    private android.widget.GridView gridView;
    private LostFoundPsotPhotoAdapter photoAdapter;
    private ArrayList<PhotoInfo> photoInfos;
    private File cameraImageFile;
    private boolean mHasDialogFrame;
    private LinearLayout ll_feedback_type;
    private TextView lostFoundTypeText;

    private RelativeLayout titlebar_iv_back;
    private RelativeLayout titlebar_iv_search;
    private TextView titlebar_tv_title;
    private TextView titlebar_tv_text_right;
    private TextView datapicker;
    private TextView timePicker;
    private TextView text;
    private ClearEditText mLostAddress;
    private ClearEditText addbbstitle;
    private EditText addbbscontent;
    private AlertView mAlertView;
    private String userId;
    private int lostFoundType = 0;
    private boolean isLost;


    @Override
    protected void initView() {
        setContentView(R.layout.activity_add_lost_found);


        //        意见反馈类型
        ll_feedback_type = (LinearLayout) findViewById(R.id.ll_feedback_type);
        lostFoundTypeText = (TextView) findViewById(R.id.tv_feedback_type_text);

        //        titlebar
        titlebar_iv_back = (RelativeLayout) findViewById(R.id.titlebar_rl_back);
        titlebar_iv_search = (RelativeLayout) findViewById(R.id.titlebar_rl_Right);
        titlebar_tv_text_right = (TextView) findViewById(R.id.titlebar_tv_text_right);
        titlebar_tv_title = (TextView) findViewById(R.id.titlebar_tv_title);

        titlebar_iv_search.setVisibility(View.GONE);
        titlebar_tv_text_right.setVisibility(View.VISIBLE);
        titlebar_tv_text_right.setText("发布");

        //     时间选择器
        datapicker = (TextView) findViewById(R.id.datapicker);
        timePicker = (TextView) findViewById(R.id.timepicker);

        this.addbbscontent = (EditText) findViewById(R.id.ed_add_bbs_content);
        this.addbbstitle = (ClearEditText) findViewById(R.id.ed_add_bbs_title);
        mLostAddress = (ClearEditText) findViewById(R.id.ed_add_lost_address);

        this.gridView = (GridView) findViewById(R.id.bbs_aad_photo);
        if (getSavedInstanceState() == null) {
            mHasDialogFrame = findViewById(R.id.frame) != null;
        }

        text = (TextView) findViewById(R.id.text);


        if (mHasDialogFrame) {
            text.setText("|");
        } else {
//            text.setText("--");
        }
    }

    @Override
    protected void initDate() {

        lostFoundType = getIntent().getIntExtra("LostFoundType", 0);
        isLost = getIntent().getBooleanExtra("isLost", true);
        if (isLost) {
            titlebar_tv_title.setText("发布寻物");
            mLostAddress.setHint("请输入物品遗失地点哦");
        } else {
            titlebar_tv_title.setText("得物寻主");
            mLostAddress.setHint("请输入捡到物品的地方哦");
        }
        lostFoundTypeText.setText(feedbackTypes[lostFoundType]);


        initImageLoader(this);
        userId = LoginUtils.getUserId(AddLostFoundActivity.this);
        photoInfos = new ArrayList<>();
        if (photoInfos.size() == 0) {
            PhotoInfo photoInfo = new PhotoInfo();
            photoInfo.setPhotoPath("res://com.flyou.henucenter/" + R.drawable.bbs_icon_add);
            photoInfos.add(photoInfo);
        }

        LostFindDataTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
    }

    @Override
    protected void setListener() {
        titlebar_iv_back.setOnClickListener(this);
        titlebar_tv_text_right.setOnClickListener(this);
        ll_feedback_type.setOnClickListener(this);
        datapicker.setOnClickListener(this);
        timePicker.setOnClickListener(this);
        addbbstitle.addTextChangedListener(this);

        photoAdapter = new LostFoundPsotPhotoAdapter(AddLostFoundActivity.this, photoInfos);
        gridView.setAdapter(photoAdapter);
        gridView.setOnItemClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titlebar_rl_back:
                AlertDialog.Builder dialog = new AlertDialog.Builder(AddLostFoundActivity.this);

                dialog.setMessage("若返回现在的编辑内容将会丢失，是否确定返回？");
                dialog.setNegativeButton("我再想想", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                dialog.show();
                break;
            case R.id.datapicker:

                FragmentManager fm = getSupportFragmentManager();
                DateTime now = DateTime.now();
                CalendarDatePickerDialogFragment calendarDatePickerDialogFragment = CalendarDatePickerDialogFragment
                        .newInstance(AddLostFoundActivity.this, now.getYear(), now.getMonthOfYear() - 1,
                                now.getDayOfMonth());
                calendarDatePickerDialogFragment.setDateRange(
                        new MonthAdapter.CalendarDay(now.getYear(), now.getMonthOfYear() - 3, now.getDayOfMonth()),
                        new MonthAdapter.CalendarDay(now.getYear(), now.getMonthOfYear() - 1, now.getDayOfMonth()));
                calendarDatePickerDialogFragment.show(fm, FRAG_TAG_DATE_PICKER);

                break;
            case R.id.timepicker:
                DateTime now1 = DateTime.now();
                RadialTimePickerDialogFragment timePickerDialog = RadialTimePickerDialogFragment
                        .newInstance(AddLostFoundActivity.this, now1.getHourOfDay(), now1.getMinuteOfHour(),
                                DateFormat.is24HourFormat(AddLostFoundActivity.this));
                if (mHasDialogFrame) {
                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

                    ft.add(R.id.frame, timePickerDialog, FRAG_TAG_TIME_PICKER)
                            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
                            .commit();
                } else {
                    timePickerDialog.show(getSupportFragmentManager(), FRAG_TAG_TIME_PICKER);
                }
                break;
            case R.id.ll_feedback_type:
                mAlertView = new AlertView("物品类型", null, null, null,
                        feedbackTypes,
                        this, AlertView.Style.ActionSheet, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {

                        currentType = feedbackTypes[position];
                        lostFoundTypeText.setText(currentType);
                        lostFoundType = position;
                    }
                });
                mAlertView.show();
                break;
            case R.id.titlebar_tv_text_right:
//                验证是否通过，并执行发布操作
                if (VerificationInput()) {
                    if (photoInfos.size() == 1) {
                        mProgressDialog = ProgressDialog.show(AddLostFoundActivity.this, null, "正在发布全校搜索令", false, false);
                        PostLostFind(null);
                    } else {
                        mProgressDialog = ProgressDialog.show(AddLostFoundActivity.this, null, "正在处理物品图片", false, false);
                        operatorBitmap();
                    }
                }
                break;

        }

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        tempCount = s;
    }

    @Override
    public void afterTextChanged(Editable s) {
        selectionStart = addbbstitle.getSelectionStart();
        selectionEnd = addbbstitle.getSelectionEnd();
        if (tempCount.length() > totalNum) {
            s.delete(selectionStart - 1, selectionEnd);
            int tempSelection = selectionEnd;
            addbbstitle.setText(s);
            addbbstitle.setSelection(tempSelection);//设置光标在最后
        }
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 100) {
                List<String> imageUploads = (List<String>) msg.obj;
                upLoadImages(imageUploads);
            }
            super.handleMessage(msg);
        }
    };

    /*
       * 上传图片
       * */
    private void upLoadImages(List<String> imageList) {


        String[] filePaths = new String[imageList.size()];
        imageList.toArray(filePaths);
        BmobProFile.getInstance(AddLostFoundActivity.this).uploadBatch(filePaths, new UploadBatchListener() {

            @Override
            public void onSuccess(boolean isFinish, String[] fileNames, String[] urls, BmobFile[] files) {
                if (isFinish) {
                    String[] fileUrls = new String[files.length];
                    for (int i = 0; i < files.length; i++) {
                        fileUrls[i] = files[i].getFileUrl(AddLostFoundActivity.this);
                    }
                    PostLostFind(fileUrls);
                }
                MyLog.d(files.length + ":::" + urls.length);
            }

            @Override
            public void onProgress(int curIndex, int curPercent, int total, int totalPercent) {
                mProgressDialog.setMessage("正在上传图片:"+curIndex+"/"+total);
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                mProgressDialog.dismiss();
            }
        });

    }

    @NonNull
    private void operatorBitmap() {
       final List<String> imageUploads =new ArrayList<>();
        new Thread(new Runnable() {
            @Override
            public void run() {

                for (int i = 0; i < photoInfos.size(); i++) {
                    if (!TextUtils.isEmpty(photoInfos.get(i).getThumbPath())) {

//                File file = BitmapTool.compressPicture(photoInfos.get(i).getPhotoPath(), userId);
                        String path = BitmapTool.getPathFromBitmap(photoInfos.get(i).getPhotoPath(), 480, 800);
                        imageUploads.add(path);

                    }
                }
                mHandler.obtainMessage(100, imageUploads).sendToTarget();
            }
        }).start();


    }


    /*
    * 发布帖子 传递 图片列表
    * */
    private void PostLostFind(String[] imageList) {
        String status = "";
        if (isLost) {
            status = Lost.LOST_BEING;
        } else {
            status = Lost.FOUND_BEING;
        }
        Lost lost = new Lost(addbbstitle.getText().toString().trim(), LostFindDataTime, mLostAddress.getText().toString().trim(), addbbscontent.getText().toString().trim(), status, lostFoundType, isLost, 1, userId, imageList,"false");

        lost.save(AddLostFoundActivity.this, new SaveListener() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
                super.onFinish();
            }

            @Override
            public void onSuccess() {
                Toast.makeText(AddLostFoundActivity.this, "success", Toast.LENGTH_SHORT).show();
                finish();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(AddLostFoundActivity.this, BmobErrorCodeUtils.getMessage(i, s), Toast.LENGTH_SHORT).show();

            }
        });


    }

    /*
    * 验证用户的输入
    * */
    private boolean VerificationInput() {
        boolean flag = true;
        if (addbbstitle.getText().toString().trim().length() == 0) {
            Toast.makeText(this, "标题不能为空，怎么可以交白卷呢？", Toast.LENGTH_SHORT).show();

            return false;
        }
        if (addbbscontent.getText().toString().length() < 20 || addbbscontent.getText().toString().length() > 2000) {
            Toast.makeText(this, "描述长度不能小于20，不能大于2000个字符", Toast.LENGTH_SHORT).show();

            return false;
        }
        if (TextUtils.isEmpty(mLostAddress.getText().toString().trim())) {
            Toast.makeText(this, "老师说，填写地址可以更好的帮助你或别人哦……", Toast.LENGTH_SHORT).show();

            return false;
        }
        return flag;
    }


    @Override
    public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {

        String month = "";
        String day = "";
        if ((monthOfYear + 1) < 10) {
            month = "0" + (monthOfYear + 1);
        } else {
            month = (monthOfYear + 1) + "";
        }
        if (dayOfMonth < 10) {
            day = "0" + dayOfMonth;
        } else {
            day = dayOfMonth + "";
        }
        datapicker.setText(year + "-" + month + "-" + day);

        LostFindDataTime = year + "-" + month + "-" + day;
    }

    @Override
    public void onTimeSet(RadialTimePickerDialogFragment dialog, int hourOfDay, int minute) {
        String hour = "";
        String min = "";
        if (hourOfDay < 10)
            hour = "0" + hourOfDay;
        else {
            hour = hourOfDay + "";
        }
        if (minute < 10) {
            min = "0" + minute;
        } else {
            min = minute + "";
        }
        timePicker.setText(hour + ":" + min);
        LostFindDataTime = LostFindDataTime + " " + hour + ":" + min;
    }

    @Override
    public void onResume() {
        // Example of reattaching to the fragment
        super.onResume();
        RadialTimePickerDialogFragment rtpd = (RadialTimePickerDialogFragment) getSupportFragmentManager().findFragmentByTag(
                FRAG_TAG_TIME_PICKER);
        if (rtpd != null) {
            rtpd.setOnTimeSetListener(this);
        }
        CalendarDatePickerDialogFragment calendarDatePickerDialogFragment = (CalendarDatePickerDialogFragment) getSupportFragmentManager()
                .findFragmentByTag(FRAG_TAG_DATE_PICKER);
        if (calendarDatePickerDialogFragment != null) {
            calendarDatePickerDialogFragment.setOnDateSetListener(this);
        }
    }

    /*
    * GridView的点击事件
    * */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (TextUtils.isEmpty(photoInfos.get(position).getThumbPath())) {
            mAlertView = new AlertView("选取图片", null, "取消", null, new String[]{"拍照", "从手机相册选择"}, AddLostFoundActivity.this, AlertView.Style.ActionSheet, this);
            mAlertView.show();
        } else {
            /*
            * 照片浏览
            * */
            Intent intent = new Intent(AddLostFoundActivity.this, GalleryActivity.class);
            intent.putExtra("position", position);
            if (photoInfos.size() == 8) {
                if (TextUtils.isEmpty(photoInfos.get(7).getThumbPath())) {
                    ArrayList<PhotoInfo> tempPhotoList;
                    tempPhotoList = photoInfos;
                    tempPhotoList.remove(7);
                    intent.putParcelableArrayListExtra("photoLists", tempPhotoList);
                } else {
                    intent.putParcelableArrayListExtra("photoLists", photoInfos);
                }
            } else {
                ArrayList<PhotoInfo> tempPhotoList;
                tempPhotoList = photoInfos;
                tempPhotoList.remove(photoInfos.size() - 1);
                intent.putParcelableArrayListExtra("photoLists", tempPhotoList);
                Toast.makeText(this, "tempPhotoList.size():" + tempPhotoList.size(), Toast.LENGTH_SHORT).show();
            }

            startActivityForResult(intent, GALLERY);
        }


    }

    /*
    * AlertView的点击事件
    * */
    @Override
    public void onItemClick(Object o, int position) {

        switch (position) {
            case 0:
                mAlertView.dismiss();
                getPhotoFromCamera();

                break;
            case 1:
                mAlertView.dismiss();
                GalleryHelper.openGalleryMuti(AddLostFoundActivity.this, 8, new GalleryImageLoader(), photoInfos);

                break;
        }
    }


    /*
  * 从相机获取
  */
    public void getPhotoFromCamera() {
        // 激活相机
        if (hasSdcard()) {

            File file = new File(SDCardUtils.getSDCardPath() + File.separator + "henucenter");
            if (!file.exists()) {
                file.mkdirs();
            }
            cameraImageFile = new File(file, System.currentTimeMillis() + ".jpg");
            //将File对象转换为Uri并启动照相程序
            Uri imageUri = Uri.fromFile(cameraImageFile);
            Intent getImageByCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //指定图片输出地址
            startActivityForResult(getImageByCamera, GalleryHelper.TAKE_REQUEST_CODE);

        }
    }

    /*
       * 判断sdcard是否被挂载
       */
    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /*
* 判断文件是否存在
*/
    public static void isExist(String path) {
        File file = new File(path);
//判断文件夹是否存在,如果不存在则创建文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /*
    * 初始化 imageLoader
    * */
    public static void initImageLoader(Context context) {

        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app
        ImageLoader.getInstance().init(config.build());
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GalleryHelper.GALLERY_REQUEST_CODE) {
            if (resultCode == GalleryHelper.GALLERY_RESULT_SUCCESS) {
                PhotoInfo photoInfo = data.getParcelableExtra(GalleryHelper.RESULT_DATA);
                List<PhotoInfo> photoInfoList = (List<PhotoInfo>) data.getSerializableExtra(GalleryHelper.RESULT_LIST_DATA);

                if (photoInfo != null) {
                    photoInfos.clear();
                    photoInfos.add(0, new PhotoInfo());
                    photoInfos.add(0, photoInfo);


                }
                if (photoInfoList != null) {
                    photoInfos.clear();
                    photoInfos.add(0, new PhotoInfo());
                    photoInfos.addAll(0, photoInfoList);
                }
                if (photoInfos.size() == 9) {
                    ArrayList<PhotoInfo> tempPhotoList = new ArrayList<>();
                    tempPhotoList = photoInfos;
                    tempPhotoList.remove(8);
                    photoAdapter = new LostFoundPsotPhotoAdapter(AddLostFoundActivity.this, tempPhotoList);
                    gridView.setAdapter(photoAdapter);
                } else {
                    photoAdapter = new LostFoundPsotPhotoAdapter(AddLostFoundActivity.this, photoInfos);
                    gridView.setAdapter(photoAdapter);
                }


            }
        }
        if (requestCode == GalleryHelper.TAKE_REQUEST_CODE) {
            if (resultCode == -1) {
                File file = BitmapTool.compressPicture(cameraImageFile.getAbsolutePath(), userId);
                PhotoInfo photoInfo = new PhotoInfo();
                photoInfo.setPhotoPath(file.getAbsolutePath());
                photoInfos.add(0, photoInfo);
                photoInfo.setThumbPath("Camera");
                photoAdapter = new LostFoundPsotPhotoAdapter(AddLostFoundActivity.this, photoInfos);
                gridView.setAdapter(photoAdapter);

            } else {
                return;
            }
        }
        if (requestCode == GALLERY && resultCode == GALLERYBACKOK) {
            ArrayList<PhotoInfo> photoList = data.getParcelableArrayListExtra("photoList");
            if (photoList.size() < 8) {
                photoInfos.clear();
                photoInfos.add(0, new PhotoInfo());
                photoInfos.addAll(0, photoList);
                photoAdapter = new LostFoundPsotPhotoAdapter(AddLostFoundActivity.this, photoInfos);
                gridView.setAdapter(photoAdapter);
            } else {
                photoInfos.clear();
                photoInfos.addAll(0, photoList);
                photoAdapter = new LostFoundPsotPhotoAdapter(AddLostFoundActivity.this, photoInfos);
                gridView.setAdapter(photoAdapter);
            }


        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            if (mAlertView != null && mAlertView.isShowing()) {
                mAlertView.dismiss();
                return false;
            }
            AlertDialog.Builder dialog = new AlertDialog.Builder(AddLostFoundActivity.this);

            dialog.setMessage("若返回现在的编辑内容将会丢失，是否确定返回？");
            dialog.setNegativeButton("我再想想", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            dialog.show();
        }

        return super.onKeyDown(keyCode, event);

    }
}
